﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 设备线程的亲缘性
{
    class Program
    {
        //获取系统运行时间毫秒级别
        [DllImport("kernel32.dll")]
        static extern uint GetTickCount();
        //SetThreadAffinityMask 指定hThread 运行在 核心 dwThreadAffinityMask
        [DllImport("kernel32.dll")]
        static extern UIntPtr SetThreadAffinityMask(IntPtr hThread, UIntPtr dwThreadAffinityMask);
        //得到当前线程的handler
        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentThread();
        static int busyTime = 10;
        static int idleTime = busyTime;
        //设置线程数目
        static int threads = 4;

        public static void changeValue(object pid)
        {
            int core =  (int)pid;

            int len = 10000000;

            uint[] data = new uint[len];

            //将当前线程绑定到指定的cpu核心上
            SetThreadAffinityMask(GetCurrentThread(), new UIntPtr(SetCpuID(core)));

            uint startTime = GetTickCount();

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            for (int i = 0; i < len; ++i)
                data[i] = GetTickCount();
            stopwatch.Stop();
            Console.WriteLine("运行时间" + stopwatch.ElapsedMilliseconds.ToString());
        }

        //获取cpu的id号
        static ulong SetCpuID(int id)
        {
            ulong cpuid = 0;
            if (id < 0 || id >= System.Environment.ProcessorCount)
            {
                id = 0;
            }
            cpuid |= 1UL << id;

            return cpuid;
        }

        /// <summary>
        /// 获取物理核心数
        /// </summary>
        /// <returns></returns>
        static int GetPhysicalCores()
        {
            int cores = 1;
            ManagementClass c = new ManagementClass(
                        new ManagementPath("Win32_Processor"));
            // Get the properties in the class
            ManagementObjectCollection moc = c.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                PropertyDataCollection properties = mo.Properties;
                //获取内核数代码
                cores = Convert.ToInt32(properties["NumberOfCores"].Value);
                string cpu = "物理内核数:" + properties["NumberOfCores"].Value + "\r";
                string total = "逻辑内核数:" + properties["NumberOfLogicalProcessors"].Value + "\r";
                Console.WriteLine(cpu);
                Console.WriteLine(total);
                //其他属性获取代码
                //foreach (PropertyData property in properties)
                //{
                //    Console.WriteLine( property.Name + ":" + property.Value + "\r");
                //}
            }
            return cores;
        }

        static void Main(string[] args)
        {
            //这里需要将Management引用
            // Get the WMI class

            GetPhysicalCores();

            //线程数目
            int num = threads;
            Console.WriteLine("线程数目" + num);
            Thread[] t = new Thread[num];
            Stopwatch stopwatch = new Stopwatch();

            for (int i = 0; i < num; ++i)
                t[i] = new Thread(new ParameterizedThreadStart(changeValue));

            stopwatch.Start();
            for (int i = 0; i < num; ++i)
            {
                t[i].Start(i);/// 2);
            }

            for (int i = 0; i < num; ++i)
                t[i].Join();

            stopwatch.Stop();
            Console.WriteLine("总运行时间" + stopwatch.ElapsedMilliseconds.ToString());
            Console.ReadKey();
        }
    }
}
